package com.innovate.cms.modules.qs.web.order;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.innovate.cms.common.config.Global;
import com.innovate.cms.common.utils.StrUtil;
import com.innovate.cms.common.web.BaseController;
import com.innovate.cms.modules.common.entity.BaseBackInfo;
import com.innovate.cms.modules.common.entity.DataBackInfo;
import com.innovate.cms.modules.qs.entity.order.DbOrder;
import com.innovate.cms.modules.qs.service.order.DbOrderService;

/**
 * 用户订单
 * 
 * @author shifangfang
 * @date 2017年12月28日 下午3:07:17
 */
@Controller
@RequestMapping(value = "/api")
public class DbOrderController extends BaseController {

	@Autowired
	private DbOrderService dbOrderService;

	@RequestMapping(value = "/v1/order/orderList", method = RequestMethod.POST)
	public @ResponseBody BaseBackInfo orderList(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
		String consumerUid = map.get("consumerUid");
		DataBackInfo<DbOrder> backInfo = new DataBackInfo<>();
		if (StrUtil.isBlank(consumerUid)) {
			BaseBackInfo info = new BaseBackInfo();
			info.setStateCode(Global.int300209);
			info.setRetMsg(Global.str300209);
			return info;
		}

		try {
			// List<DbOrder> orderss = genOrder();
			// for (DbOrder order : orderss) {
			// dbOrderService.saveOrder(order);
			// }

			// 获取用户订单列表
			List<DbOrder> orders = dbOrderService.orderList(consumerUid);
			backInfo.setStateCode(Global.intYES);
			backInfo.setRetMsg(Global.SUCCESS);
			backInfo.setData(orders);
		} catch (Exception e) {
			logger.debug("[" + Thread.currentThread().getStackTrace()[1].getClassName() + " - " + Thread.currentThread().getStackTrace()[1].getMethodName() + "()接口报错：{}]", e.getMessage());
			backInfo.setRetMsg(Global.ERROR);
			backInfo.setStateCode(Global.intNO);
		}
		return backInfo;
	}

	@RequestMapping(value = "/v1/order/businessOrderList", method = RequestMethod.POST)
	public @ResponseBody BaseBackInfo businessOrderList(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
		String businessUid = map.get("businessUid");
		DataBackInfo<DbOrder> backInfo = new DataBackInfo<>();
		if (StrUtil.isBlank(businessUid)) {
			BaseBackInfo info = new BaseBackInfo();
			info.setStateCode(Global.int300209);
			info.setRetMsg(Global.str300209);
			return info;
		}

		try {
			// List<DbOrder> orderss = genOrder();
			// for(DbOrder order:orderss){
			// dbOrderService.saveOrder(order);
			// }

			// 获取商户订单列表
			List<DbOrder> orders = dbOrderService.businessOrderList(businessUid);
			backInfo.setStateCode(Global.intYES);
			backInfo.setRetMsg(Global.SUCCESS);
			backInfo.setData(orders);
		} catch (Exception e) {
			logger.debug("[" + Thread.currentThread().getStackTrace()[1].getClassName() + " - " + Thread.currentThread().getStackTrace()[1].getMethodName() + "()接口报错：{}]", e.getMessage());
			backInfo.setRetMsg(Global.ERROR);
			backInfo.setStateCode(Global.intNO);
		}
		return backInfo;
	}

	/**
	 * 核销-商家确认客户到店铺消费
	 * 
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/v1/order/verifyConsumption", method = RequestMethod.POST)
	public @ResponseBody BaseBackInfo verifyConsumption(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {

		String tradeNo = map.get("tradeNo");
		// String consumeStateStr = map.get("consumeState");

		DbOrder order = dbOrderService.orderInfo(tradeNo);

		DataBackInfo<DbOrder> backInfo = new DataBackInfo<>();
		if (StrUtil.isBlank(tradeNo)) {
			BaseBackInfo info = new BaseBackInfo();
			info.setStateCode(Global.int300209);
			info.setRetMsg(Global.str300209);
			return info;
		}
		try {
			int consumeState = 1;
			Calendar now = Calendar.getInstance();
			now.set(Calendar.HOUR_OF_DAY, 23);
			now.set(Calendar.MINUTE, 59);
			now.set(Calendar.SECOND, 59);

			// 如果订单有效时间当天，说明已经过期
			if (order.getMsgEndDate().getTime() < now.getTimeInMillis()) {
				consumeState = 2;
			}
			// 商家核销订单
			dbOrderService.verifyConsumption(tradeNo, consumeState);
			if (consumeState==2) {
				order.setConsumeState(consumeState);
				backInfo.setStateCode(Global.intNO);
				backInfo.setRetMsg(Global.FALSE);
			}else {
				order.setConsumeState(consumeState);
				backInfo.setStateCode(Global.intYES);
				backInfo.setRetMsg(Global.SUCCESS);
			}
		
			List<DbOrder> listOrders = new ArrayList<>();
			listOrders.add(order);
			backInfo.setData(listOrders);
		} catch (Exception e) {
			logger.debug("[" + Thread.currentThread().getStackTrace()[1].getClassName() + " - " + Thread.currentThread().getStackTrace()[1].getMethodName() + "()接口报错：{}]", e.getMessage());
			backInfo.setRetMsg(Global.ERROR);
			backInfo.setStateCode(Global.intNO);
		}
		return backInfo;
	}

	@RequestMapping(value = "/v1/order/orderInfo", method = RequestMethod.POST)
	public @ResponseBody BaseBackInfo orderInfo(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {

		String tradeNo = map.get("tradeNo");

		DataBackInfo<DbOrder> backInfo = new DataBackInfo<>();
		if (StrUtil.isBlank(tradeNo)) {
			BaseBackInfo info = new BaseBackInfo();
			info.setStateCode(Global.int300209);
			info.setRetMsg(Global.str300209);
			return info;
		}
		try {
			// 订单/核销详情
			DbOrder order = dbOrderService.orderInfo(tradeNo);
			ArrayList<DbOrder> list = new ArrayList<>();
			backInfo.setStateCode(Global.intYES);
			backInfo.setRetMsg(Global.SUCCESS);
			if (null != order) {
				list.add(order);
			}

			backInfo.setData(list);
		} catch (Exception e) {
			logger.debug("[" + Thread.currentThread().getStackTrace()[1].getClassName() + " - " + Thread.currentThread().getStackTrace()[1].getMethodName() + "()接口报错：{}]", e.getMessage());
			backInfo.setRetMsg(Global.ERROR);
			backInfo.setStateCode(Global.intNO);
		}
		return backInfo;
	}

	public static List<DbOrder> genOrder() {
		List<DbOrder> orders = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			DbOrder dbOrder = new DbOrder();
			// 生成订单号
			dbOrder.setTradeNo(genTradeNo());
			dbOrder.setConsumerUid("04265594a4ee456a8954ea65dca8733b");
			dbOrder.setMobile("13553846634");
			dbOrder.setMid(102);
			dbOrder.setPrice(128.00d);
			dbOrder.setNum(1);
			dbOrder.setPayType(0);
			orders.add(dbOrder);
		}
		return orders;
	}

	/**
	 * 生成16位订单号
	 * 
	 * @return
	 */
	public static String genTradeNo() {
		int first = new Random().nextInt(8) + 1;
		int hashCodeV = UUID.randomUUID().toString().hashCode();
		if (hashCodeV < 0) {// 有可能是负数
			hashCodeV = -hashCodeV;
		}
		return first + String.format("%015d", hashCodeV);
	}

}
